package com.rongshu.sendmessage.activity;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.HuoYunBean;
import com.rongshu.sendmessage.bean.WebDataBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.ProgressDialog;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.view.TitileLayout;

import java.util.HashMap;
import java.util.Map;


public class WebViewActivity extends BaseActivity {
    private WebView about_wv;
    private boolean isHead;
    private TitileLayout titleView;
    private ProgressDialog dialog;
    private String type;

    //private ImageView back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        setContentView(R.layout.activity_play_video_web_view);
        isHead = getIntent().getBooleanExtra("isHead", false);
        titleView = (TitileLayout) findViewById(R.id.titleView);
        String source = getIntent().getStringExtra("source");
        if ("help".equals(source)) {
            titleView.setTitle("帮助中心");
            type="USE_HELP";
        } else if ("xieyi".equals(source)) {
            titleView.setTitle("服务协议");
            type="service_agreement";
        } else if ("yinsi".equals(source)) {
            titleView.setTitle("隐私政策");
            type="privacy_policy";
        }else if ("guanyu".equals(source)) {
            titleView.setTitle("关于我们");
            type="ABOUT_US";
        }
        titleView.hideRight();
        titleView.setTitleClickListener(new TitileLayout.TitleClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {

            }

            @Override
            public void onTitleClick() {

            }
        });
        about_wv = (WebView) findViewById(R.id.address_wv);
        initWebVIew();
        initData();
    }

    public void showProgress() {
        dialog = ProgressDialog.createDialog(this);
        dialog.show();
    }

    public void hideProgress() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }
    private void initData() {
        //

        showProgress();
        Map<String, String> param = new HashMap<String, String>();
        param.put("baseDataMessageType", type);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        OkGo.<String>post(new HYContent().GET_WEB_URL).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {//Driver司机，VehicleOwner车主
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(), false);
                Log.d("user", response.body());
                final int code = jr.getCode();
                if (code > 0) {
                    WebDataBean huoYunBean = JSONObject.toJavaObject(jr.getData(), WebDataBean.class);
                    if (huoYunBean != null) {
                        String content = huoYunBean.getContent();
                        about_wv.loadData(
                                StringUtils.isEmpty(content)?"":content,
                                "text/html; charset=UTF-8", null);//"utf-8"
                    } else {
                        ToastUtils.show(mContext, "服务器繁忙请重试！");
                    }
                } else {
                    ToastUtils.show(mContext, jr.getMsg());
                }
                hideProgress();
            }

            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext, "操作失败");
                hideProgress();
                String body = response.body();


            }
        });

    }

    private void initWebVIew() {
        WebSettings webSettings = about_wv.getSettings();
        WebSettings ws = about_wv.getSettings();
        ws.setBuiltInZoomControls(true);// 隐藏缩放按钮
        ws.setDisplayZoomControls(false);
        ws.setJavaScriptEnabled(true);//允许使用js
        ws.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setDisplayZoomControls(false);
        about_wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                super.onReceivedSslError(view, handler, error);
                handler.proceed();// 接受所有网站的证书
            }
        });
        about_wv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(Intent.ACTION_DIAL);
//                Uri date = Uri.parse("tel:" + data.getOrganizationPhone().trim());
//                intent.setData(date);
//                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("ansen", "是否有上一个页面:" + about_wv.canGoBack());
        if (about_wv.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            about_wv.goBack(); // goBack()表示返回webView的上一页面
        } else if (!about_wv.canGoBack()) {
            finish();
        }
        return true;
    }


    /**
     * Android 关闭WebView之后，声音或者视频不停止的解决办法
     * 清除webview释放内存防止oom
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        about_wv.reload();
        about_wv.removeAllViews();
        about_wv.destroy();
        finish();
    }

}


